package com.shj.shiro.controller;

import java.util.List;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.shj.shiro.model.Resource;
import com.shj.shiro.model.User;
import com.shj.shiro.service.ShiroService;
import com.shj.shiro.util.ShiroUtils;
import com.shj.shiro.vo.IndexPageVO;

@Controller
public class LoginController {
	
	@Autowired
	private ShiroService shiroService;
	
	@Autowired
	private HttpServletRequest request;

	@RequestMapping("/login")
    public ModelAndView goTologin(){
        ModelAndView mav = new ModelAndView("login");
        return mav;
    }
	
	@RequestMapping("/index")
	public String gotoIndex(){
		return "index";
	}
	
	@RequestMapping("/validateLogin")
	@ResponseBody
	public String validateLogin(){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return "Success";
		} catch (AuthenticationException e) {
			return "用户或密码错误";
		}
	}
	
	@RequestMapping("/getIndexInfo")
	@ResponseBody
	public IndexPageVO getInfoOfIndexPage(){
		IndexPageVO vo = new IndexPageVO();
		User user = ShiroUtils.getUser();
		vo.setUser(user);
		
		List<Resource> menus = shiroService.getMenus();
		vo.setMenus(menus);
		
		return vo;
	}
}
